package top.zerozoo.learn.grade.servlet;

import top.zerozoo.learn.grade.entity.CourseScore;
import top.zerozoo.learn.grade.factory.ServiceFactory;
import top.zerozoo.learn.grade.service.CourseScoreService;
import top.zerozoo.learn.grade.service.StudentService;
import top.zerozoo.learn.grade.util.NumberUtils;
import top.zerozoo.learn.grade.vo.StudentInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/studentDetail.do")
public class StudentDetailServlet extends HttpServlet {
    private final StudentService studentService = ServiceFactory.get(StudentService.class);
    private final CourseScoreService courseScoreService = ServiceFactory.get(CourseScoreService.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = NumberUtils.parse(req.getParameter("id"), Integer.class, -1);
        StudentInfo studentInfo = studentService.find(id);

        if (studentInfo == null) {
            req.setAttribute("error_msg", "该学生不存在或已被删除");
            req.getRequestDispatcher("/studentDetail.jsp").forward(req, resp);
            return;
        }
        List<CourseScore> courseScores = courseScoreService.findByStudentID(studentInfo.getId());
        req.setAttribute("studentInfo", studentInfo);
        req.setAttribute("courseScores", courseScores);

        req.getRequestDispatcher("/studentDetail.jsp").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
